import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/zh-CN'
import App from './App'
import router from './router'
import store from './store'
import * as filters from './filters' // 全局filter
import '@/icons' // icon
import '@/permission' // 权限
import { setToken, setReToken, removeToken } from '@/utils/auth'

Vue.use(ElementUI, { locale })

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
// 监听接收消息
window.addEventListener('message', function(event) {
  // 判断是不是父窗口的消息
  if (event.source !== window.parent) return
  console.log('子系统收到消息 ===>')
  console.log('origin: ' + event.origin)
  // console.log('data: ' + event.data)

  // 退出
  if (event.data === 'logout') {
    store.commit('SET_TOKEN', '')
    store.commit('SET_REFRESH_TOKEN', '')
    store.commit('SET_ROLES', [])
    removeToken()
  }

  // 接收token
  try {
    var args = JSON.parse(event.data)
    if (args && args.access_token && args.refresh_token) {
      setToken(args.access_token)
      setReToken(args.refresh_token)
      // store.commit('SET_TOKEN', args.access_token)// 更改SET_TOKEN
      // store.commit('SET_REFRESH_TOKEN', args.refresh_token)// 更改SET_REFRESH_TOKEN
    }
  } catch (error) {
    // 接收消息异常
  }
})
